<template>
  <div class="p-2">
    <el-card shadow="never" v-show="showSearch">
      <el-form
        :model="queryParams"
        ref="queryOrganizationRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="区域名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入区域名称"
            clearable
            @keyup.enter="handleOrganizationQuery"
          />
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" clearable placeholder="请选择">
            <el-option
              v-for="item in rootOrganizationTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="Search"
            @click="handleOrganizationQuery"
          >
            搜索
          </el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

  <div class="p-2">
    <el-card shadow="never">
      <!-- 按钮区 -->
      <!-- <template #header>
        <el-row :gutter="10" class="mb-1">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Edit"
              @click="handleAdd()"
              v-hasPermi="['system:user:edit']"
            >
              新增文章
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleEditNews()"
              v-hasPermi="['system:user:edit']"
            >
              编辑
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['system:user:remove']"
            >
              删除
            </el-button>
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getNewsList"
          ></right-toolbar>
        </el-row>
      </template> -->

      <el-table
        v-loading="loading"
        :data="organizationList"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        ref="treeTableRef"
      >
        <el-table-column label="机构名称" align="left" prop="name" />

        <!--        <el-table-column label="状态" prop="status" width="80">-->
        <!--          <template #default="{ row }">-->
        <!--            <el-tag :type="CommonStatusStyleTypeMap.get(row.status)"-->
        <!--            >{{ row.statusMsg }}-->
        <!--            </el-tag>-->
        <!--          </template>-->
        <!--        </el-table-column>-->

        <el-table-column label="类型" align="center" prop="typeMsg" />

        <el-table-column
          label="所属区域"
          align="center"
          prop="regionMergerName"
          width="180"
        />

        <el-table-column label="创建时间" align="center" prop="createTime" />

        <!--        <el-table-column-->
        <!--          label="排序"-->
        <!--          align="center"-->
        <!--          width="60"-->
        <!--          prop="orderNum"-->
        <!--        />-->

        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <span v-hasPermi="['school:article:edit']">
              <el-tooltip content="编辑文章" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleEditArticle(scope.row)"
                />
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        v-show="organizationTotal > 0"
        :total="organizationTotal"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getOrganizationList"
      />
    </el-card>

    <!-- 文章列表 -->
    <el-dialog
      v-model="dialogStatus.articleTable"
      title="文章列表"
      width="80%"
      center
      append-to-body
      :show-close="true"
      @close="handelCloseArticleDialog"
    >
      <!-- <template #header> -->
      <el-row :gutter="10" class="mb-1">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Edit"
            @click="handleAdd()"
            v-hasPermi="['school:article:add']"
          >
            新增文章
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleEditNews()"
            v-hasPermi="['school:article:edit']"
          >
            编辑
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete()"
            v-hasPermi="['school:article:delete']"
          >
            删除
          </el-button>
        </el-col>
        <right-toolbar
          :search="false"
          @queryTable="getNewsList"
        ></right-toolbar>
      </el-row>
      <!-- </template> -->
      <el-table
        :data="newsList"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="30" align="center" />
        <el-table-column label="分类标题" align="center" prop="articleType">
          <template #default="{ row }: { row: SchoolSiteArticleVo }">
            <el-tag>
              {{ articleTypeMap.get(row.articleType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="文章标题" align="center" prop="title" />
        <el-table-column label="文章副标题" align="center" prop="subTitle" />
        <el-table-column label="创建者" align="center" prop="createBy" />
        <el-table-column label="封面" prop="status" align="center">
          <template #default="{ row }: { row: SchoolSiteArticleVo }">
            <el-image
              style="width: 100px; height: 100px"
              :src="row.cover"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :initial-index="1"
              :preview-src-list="row.cover"
              fit="scale-down"
            />
          </template>
        </el-table-column>

        <el-table-column label="链接" align="center" prop="content">
          <template #default="{ row }: { row: SchoolSiteArticleVo }">
            <!--  -->
            <span v-if="row.contentType === '1'"> {{ row.content }} </span>
            <span v-else> 暂无链接 </span>
          </template>
        </el-table-column>
        <el-table-column label="轮播" prop="status" align="center">
          <template #default="{ row }: { row: SchoolSiteArticleVo }">
            <el-tag
              :type="CommonStatusStyleTypeMap.get(row.isTop ?? '') ?? 'info'"
            >
              {{ isSwiperMap.get(row.isTop ?? "") }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="状态" prop="status" align="center">
          <template #default="{ row }: { row: SchoolSiteArticleVo }">
            <el-tag
              :type="CommonStatusStyleTypeMap.get(row.status ?? '') ?? 'info'"
            >
              {{ row.statusMsg }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-tooltip content="详情" placement="top" :enterable="false">
              <el-button
                link
                type="primary"
                icon="FolderOpened"
                @click="handleDetail(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top" :enterable="false">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleEditNews(scope.row)"
                v-hasPermi="['school:article:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" :enterable="false">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['school:article:delete']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParamsBO.pageNum"
        v-model:limit="queryParamsBO.pageSize"
        @pagination="getNewsList"
      />
    </el-dialog>

    <!-- 新建、编辑新闻 -->
    <el-dialog
      v-model="dialogStatus.visible"
      :title="dialogStatus.title"
      width="80%"
      center
      append-to-body
      :show-close="true"
      @close="handleCloseDialog"
      :before-close="handleBeforeCloseDialog"
    >
      <el-form
        :model="dialogData"
        ref="dialogFormRef"
        :inline="true"
        label-width="100px"
        class="dialogForm"
        :rules="formRules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="新闻标题" prop="title">
              <el-input
                v-model="dialogData.title"
                :disabled="dialogStatus.isDisabled"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="新闻副标题" prop="subTitle">
              <el-input
                v-model="dialogData.subTitle"
                :disabled="dialogStatus.isDisabled"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="6">
            <el-form-item label="详细类别" prop="articleType">
              <el-select
                v-model="dialogData.articleType"
                :disabled="dialogStatus.isDisabled"
                clearable
                placeholder="详细类别"
              >
                <el-option
                  v-for="item in selectArr.newsTypeArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item
              label="是否轮播"
              prop="isTop"
              :disabled="dialogStatus.isDisabled"
            >
              <el-select
                v-model="dialogData.isTop"
                :disabled="dialogStatus.isDisabled"
                clearable
                placeholder="是否轮播"
              >
                <el-option
                  v-for="item in selectArr.isTopArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-form-item label="新闻封面" prop="cover">
            <upload-school-article-cover
              v-if="dialogStatus.visible"
              @getCoverUrl="getCoverUrl"
              :cover-type="1"
              :organization-id="dialogStatus.organizationId"
              :is-linked="dialogStatus.isLinked"
              :linked-cover-url="dialogStatus.cover"
              :crop-width="200"
              :crop-height="200"
              v-model="dialogStatus.isSelected"
              :is-operable="dialogStatus.dialogMode === DialogModeEnum.EDIT"
            ></upload-school-article-cover>
          </el-form-item>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="文章类型" prop="contentType">
              <el-radio-group
                :disabled="dialogStatus.isDisabled"
                v-model="dialogData.contentType"
                size="ml-4"
                @change="handleRadioChange"
              >
                <el-radio label="1" size="large">外部链接</el-radio>
                <el-radio label="2" size="large">富文本</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="自动摘要">
              <el-checkbox
                v-model="dialogData.autoCreateIntroduction"
                :disabled="
                  dialogStatus.isDisabled ||
                  dialogStatus.isDisableAutoCreateIntroduction
                "
                @change="handleAutoCreateIntroductionChange"
              ></el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="文章摘要" prop="introduction">
              <div class="flex" style="flex: 1">
                <el-input
                  v-model="dialogData.introduction"
                  :disabled="
                    dialogStatus.isDisabled ||
                    dialogStatus.isDisableIntroduction
                  "
                  maxlength="256"
                  placeholder="请输入摘要"
                  rows="4"
                  type="textarea"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="dialogData.contentType === '2'">
          <el-col :span="24">
            <el-form-item label="页面内容" prop="content">
              <div style="border: 1px solid #ccc" v-loading="editorLoading">
                <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editorRef"
                  :disabled="dialogStatus.isDisabled"
                  :defaultConfig="toolbarConfig"
                  mode="default"
                />
                <editor
                  style="height: 400px; overflow-y: hidden"
                  v-model="currentRichContent"
                  :defaultConfig="editorConfig"
                  mode="default"
                  @onCreated="handleCreated"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="dialogData.contentType === '1'">
          <el-col :span="24">
            <el-form-item label="链接" prop="link">
              <el-input
                v-model="currentLinkContent"
                :disabled="dialogStatus.isDisabled"
                placeholder="请输入外部链接"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button type="primary" icon="Check" @click="dialogSubmit">
          提交
        </el-button>
        <el-button icon="Close" @click="dialogStatus.visible = false"
          >关闭
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import {
  getOssAuth as getOssAuthApi,
  postToOSS as postToOSSApi,
  addSchoolNews as addSchoolNewsApi,
  getSchoolNewsList as getSchoolNewsListApi,
  getSchoolNewsDetail as getSchoolNewsDetailApi,
  updateSchoolNews as updateSchoolNewsApi,
  deleteSchoolNews as deleteSchoolNewsApi,
  getRootOrganizationTypeList as getRootOrganizationTypeListApi,
  getRootOrganizationList as getRootOrganizationListApi,
} from "@/service/api/school/news";

import RightToolbar from "@/components/RightToolbar/index.vue";
import Pagination from "@/components/Pagination/index.vue";
import {
  SchoolSiteArticleVo,
  SysDictDataVo,
  SysOrganizationVo,
} from "@/service/api/school/news/types.ts";
import { BasePageResponse, BaseResponse } from "@/service/api/type.ts";
import { to } from "await-to-js";
import {
  CommonStatusMap,
  CommonStatusStyleTypeMap,
  articleTypeMap,
  isSwiperMap,
} from "@/maps/commonMaps.ts";
import { IToolbarConfig } from "@wangeditor/editor";
import { DialogModeEnum } from "@/enums/dialogEnum.ts";

/**
 * 表单校验规则
 */
const formRules = {
  title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
  articleType: [
    { required: true, message: "新闻类型不能为空", trigger: "blur" },
  ],
  isTop: [{ required: true, message: "是否轮播不能为空", trigger: "blur" }],
  introduction: [
    {
      validator: (rule: any, value: any, callback: any) => {
        // 链接类型摘要必填
        if (dialogData.value.contentType == "1") {
          if (
            dialogData.value.introduction == null ||
            dialogData.value.introduction == ""
          ) {
            return callback(new Error("摘要不能为空"));
          }
        }
        // 富文本类型摘要，需要判断
        else if (dialogData.value.contentType == "2") {
          // 如果未选择自动生成摘要
          if (!dialogData.value.autoCreateIntroduction) {
            if (
              dialogData.value.introduction == null ||
              dialogData.value.introduction == ""
            ) {
              return callback(new Error("摘要不能为空"));
            }
          }
        }
        callback();
      },
      trigger: "blur",
    },
  ],
  link: [
    {
      validator: (rule: any, value: any, callback: any) => {
        console.log(value);
        // 链接类型链接必填
        if (dialogData.value.contentType == "1") {
          if (value == null || value == "") {
            return callback(new Error("链接不能为空"));
          }
        }
        callback();
      },
      trigger: "blur",
    },
  ],
  content: [
    {
      validator: (rule: any, value: any, callback: any) => {
        console.log(value);
        // 富文本类型内容必填
        if (dialogData.value.contentType == "2") {
          if (value == null || value == "") {
            return callback(new Error("文章内容不能为空"));
          }
        }
        callback();
      },
      trigger: "blur",
    },
  ],
  // content: [{ required: true, message: "新闻内容不能为空", trigger: "blur" }],
};

// 知识列表
const newsList = ref<SchoolSiteArticleVo[]>([]);
const total = ref(0);
const dialogFormRef = ref(ElForm);
const queryFormRef = ref(ElForm);
// 获取凭证BO
const getOssAuthBO = reactive({
  originalFileName: "",
});
// 上传图片到OSSBO
const initUploadImgBO = {
  OSSAccessKeyId: "",
  callback: "",
  expire: "",
  host: "",
  policy: "",
  signature: "",
  key: "",
};
// 获取知识列表BO
const initQueryParams = {
  id: "",
  status: "",
  pageSize: 10,
  pageNum: 1,
  title: "",
  sendTime: "",
  content: "",
  cover: "",
  introduction: "",
  // isTop: false,
  siteType: "",
  articleType: "",
  url: "",
  isRich: false,
  timeRange: [null, null],
  orderByColumn: "createTime",
  orderType: "desc",
  organizationId: "",
  // delFlag:'0'
};
const initDialogStatus = {
  dialogMode: DialogModeEnum.DETAIL,
  isDisabled: false,
  preview: false,
  visible: false,
  articleTable: false,
  title: "",
  isLinked: false,
  articleTableTitle: "",
  cover: "",
  isSelected: false,
  organizationId: "",
  isDisableIntroduction: false,
  isDisableAutoCreateIntroduction: true,
};

const initDialogData: SchoolSiteArticleVo & {
  autoCreateIntroduction: boolean;
} = {
  id: "",
  status: "0",
  title: "",
  createTime: undefined,
  content: "",
  cover: "",
  introduction: "",
  isTop: false,
  articleType: "",
  contentType: "1",
  organizationId: "",
  autoCreateIntroduction: false,
};
//
const BO = reactive({
  uploadImgBO: { ...initUploadImgBO },
  queryParamsBO: { ...initQueryParams },
  dialogData: { ...initDialogData },
  dialogStatus: { ...initDialogStatus },
});
const { uploadImgBO, queryParamsBO, dialogData, dialogStatus } = toRefs(BO);

const rootOrganizationTypeMap = ref<Map<string, string>>(new Map());
const schoolOrganizationType = ref();

// 选择框
const selectArr = ref({
  siteTypeArr: [
    {
      value: "1",
      label: "家校共育",
    },
    {
      value: "2",
      label: "家校动态",
    },
  ],
  newsTypeArr: [
    {
      value: "0",
      label: "理念介绍",
    },
    {
      value: "1",
      label: "政策解读",
    },
    {
      value: "2",
      label: "热点新闻",
    },
    {
      value: "3",
      label: "共育活动",
    },
  ],
  isTopArr: [
    {
      value: true,
      label: "是",
    },
    {
      value: false,
      label: "否",
    },
  ],
  typeArr: [
    {
      value: "0",
      label: "其他类型",
    },
    {
      value: "1",
      label: "学校类型",
    },
    {
      value: "2",
      label: "班级类型",
    },
    {
      value: "3",
      label: "教育机构类型",
    },
    {
      value: "4",
      label: "专家组织类型",
    },
    {
      value: "5",
      label: "工作室类型",
    },
    {
      value: "6",
      label: "年级类型",
    },
    {
      value: "7",
      label: "公司类型",
    },
  ],
});
const rootOrganizationTypeList = ref<SysDictDataVo[]>([]);
/**
 * 获取根组织类型
 */
const getRootOrganizationTypeList = async (): Promise<boolean> => {
  const [err, res] = await to<BasePageResponse<SysDictDataVo>, any>(
    getRootOrganizationTypeListApi(),
  );
  if (!err) {
    rootOrganizationTypeList.value = res?.rows ?? [];
    rootOrganizationTypeList.value.forEach((item) => {
      rootOrganizationTypeMap.value.set(item.value ?? "", item.label);
      if (item.label === "学校") {
        schoolOrganizationType.value = item;
      }
      console.log(schoolOrganizationType.value);
    });

    return true;
  }

  return false;
};

// 查询机构的bo
const queryParams = reactive({
  name: "",
  type: "",
  parentId: 0,
  orderByColumn: "createTime",
  orderType: "desc",
  pageSize: 10,
  pageNum: 1,
});
const organizationTotal = ref(0);

// 树结构数据
const organizationList = ref<SysOrganizationVo[]>([]);
/**
 * 获取组织树
 */
const getOrganizationList = async (): Promise<boolean> => {
  // queryParams.type = schoolOrganizationType.value.value;
  const [err, res] = await to<BasePageResponse<SysOrganizationVo>, any>(
    getRootOrganizationListApi(queryParams),
  );
  if (!err) {
    console.log(res);
    organizationList.value = res?.rows ?? [];
    organizationTotal.value = Number(res?.total);

    organizationList.value.forEach((item) => {
      item.typeMsg = rootOrganizationTypeMap.value.get(item.type);
    });

    return true;
  }
  return false;
};
/**
 * 处理编辑封面按钮
 * @param row
 */
const handleEditArticle = async (row: any) => {
  loading.value = true;
  queryParamsBO.value.organizationId = row.id;
  dialogData.value.organizationId = row.id;
  console.log(row, dialogData.value);
  dialogStatus.value.articleTableTitle = "组织文章列表";
  const [err, res] = await to(getNewsList());
  if (!err) {
    // dialogStatus.value.covers = res?.rows ?? [];
    dialogStatus.value.articleTable = true;
  }
  loading.value = false;
};
/**
 * 获取新闻列表
 */
const getNewsList = async (): Promise<boolean> => {
  let [err, res] = await to<BasePageResponse<SchoolSiteArticleVo>, any>(
    getSchoolNewsListApi(queryParamsBO.value),
  );
  if (!err) {
    newsList.value = res?.rows ?? [];
    total.value = Number(res?.total ?? 0);
    newsList.value.forEach((item) => {
      item.statusMsg = CommonStatusMap.get(item.status ?? "") ?? "未知";
    });
    return true;
  }
  return false;
};

const editorLoading = ref<boolean>(false);

const loading = ref(false);
const single = ref(true);
const ids = ref([]);
const multiple = ref(true);
const showSearch = ref(true);

/**
 * 多选框选中数据
 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  console.log(ids.value);
};

/**
 * 获取学校新闻详情
 * @param id
 */
const getSchoolNewsDetail = async (id: string): Promise<boolean> => {
  let [err, res] = await to<BaseResponse<SchoolSiteArticleVo>, any>(
    getSchoolNewsDetailApi(id),
  );
  if (!err) {
    console.log(res);
    dialogData.value = res?.data ?? initDialogData;
    dialogData.value.autoCreateIntroduction = false;
    if (dialogData.value.cover && dialogData.value.cover != "") {
      dialogStatus.value.cover = dialogData.value.cover;
      dialogStatus.value.isLinked = true;
    }
    dialogStatus.value.isDisableIntroduction = false;
    if (dialogData.value.contentType === "1") {
      // 链接
      currentLinkContent.value = dialogData.value.content;
    } else {
      // 富文本
      currentRichContent.value = dialogData.value.content;
    }
    return true;
  }
  return false;
};

// 富文本编辑器工具栏配置
const toolbarConfig: IToolbarConfig = {
  excludeKeys: ["group-video", "fullScreen"],
};

// 配置editor
const editorConfig = {
  placeholder: "请输入新闻内容...",
  MENU_CONF: {
    uploadImage: {
      customUpload: {},
    },
  },
};
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

const handleCreated = (editor: any) => {
  editorRef.value = editor;
  console.log("created", editor);
};

/**
 * 处理详情按钮
 * @param row
 */
const handleDetail = async (row: any) => {
  loading.value = true;
  dialogStatus.value.dialogMode = DialogModeEnum.DETAIL;
  console.log(dialogStatus.value.dialogMode);
  dialogFormRef.value?.clearValidator();

  const response = await getSchoolNewsDetail(row.id);

  if (response) {
    dialogStatus.value.title = "学校新闻详情";
    console.log(editorRef.value);
    // 这是个异步方法！！！！！！必须用await
    (await editorRef.value) && editorRef.value.disable();
    dialogStatus.value.isDisabled = true;
    dialogStatus.value.visible = true;
    nextTick(() => {
      dialogFormRef.value?.clearValidate();
    });
    loading.value = false;
  }
};

/**
 * 编辑按钮
 * @param row
 */
const handleEditNews = async (row?: any) => {
  dialogStatus.value.dialogMode = DialogModeEnum.EDIT;

  console.log(dialogStatus.value.dialogMode);

  loading.value = true;
  const id = row?.id ?? ids.value[0];
  const response = await getSchoolNewsDetail(id);
  if (response) {
    dialogStatus.value.isDisabled = false;
    editorRef.value && editorRef.value.enable();
    dialogStatus.value.title = "编辑学校新闻";
    dialogStatus.value.isDisabled = false;
    dialogStatus.value.visible = true;
    loading.value = false;
  }
};

/**
 * 处理新增按钮
 */
const handleAdd = () => {
  dialogStatus.value.dialogMode = DialogModeEnum.EDIT;
  dialogStatus.value.title = "新增学校新闻";
  dialogStatus.value.visible = true;
  dialogStatus.value.isDisableIntroduction = false;
  nextTick(() => {
    dialogFormRef.value?.clearValidator();
  });
};

/**
 * 处理删除按钮
 * @param row
 */
const handleDelete = async (row?: any) => {
  // 询问确认删除
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("是否确认删除新闻，删除后将不可恢复", "警告", {
      type: "warning",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
    }),
  );

  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消删除",
    });
  } else if (confirm === "confirm") {
    const _ids = row?.id ?? ids.value;
    console.log(_ids);

    await to<BaseResponse<any>, any>(deleteSchoolNewsApi(_ids));
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    getNewsList();
  }
};

/**
 * 获取上传凭证
 */
const getOssAuth = async () => {
  const res = await getOssAuthApi(getOssAuthBO);
  uploadImgBO.value = res;
  console.log(res);
};

// 获取图片base64
const getBase64 = (file: File) => {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    let imgResult = "";
    reader.readAsDataURL(file);
    reader.onload = function () {
      imgResult = reader.result;
    };
    reader.onerror = function (error) {
      reject(error);
    };
    reader.onloadend = function () {
      resolve(imgResult);
    };
  });
};

// 上传到oss
const upload = async (file: File) => {
  getOssAuthBO.originalFileName = file.name;
  await getOssAuth();
  const formData = new FormData();
  formData.append("key", uploadImgBO.value.key);
  formData.append("OSSAccessKeyId", uploadImgBO.value.OSSAccessKeyId);
  formData.append("policy", uploadImgBO.value.policy);
  formData.append("signature", uploadImgBO.value.signature);
  formData.append("callback", uploadImgBO.value.callback);
  formData.append("file", file); // 一定在最后
  console.log(formData);
  const res = await postToOSSApi(formData);
  console.log(res);
  return res;
};

// 自定义上传图片
editorConfig.MENU_CONF["uploadImage"] = {
  // 自定义上传
  async customUpload(file: File, insertFn: any) {
    // file 即选中的文件
    // const res = await upload(file);
    // console.log(res);
    // if (res.data.code === 200) {
    //   // 自己实现上传，并得到图片 url alt href
    //   // 最后插入图片
    //   insertFn(res.data.data.url);
    // } else {
    //   ElMessage({
    //     type: "error",
    //     message: "失败",
    //   });
    // }
    const res = await getBase64(file);
    console.log(res);
    insertFn(res);
  },
};

const currentLinkContent = ref();
const currentRichContent = ref();
// 改变radio选择值
const handleRadioChange = (value: any) => {
  console.log(value, typeof value);

  // 链接
  if (value == "1") {
    // currentLinkContent.value = dialogData.value.content;
    dialogData.value.autoCreateIntroduction = false;
    dialogStatus.value.isDisableIntroduction = false;
    dialogStatus.value.isDisableAutoCreateIntroduction = true;
  }
  // 富文本
  else if (value == "2") {
    dialogStatus.value.isDisableAutoCreateIntroduction = false;
  }
};

// 关闭文章列表dialog
const handelCloseArticleDialog = () => {
  dialogStatus.value = Object.assign({}, initDialogStatus);
  loading.value = false;
};

// 关闭dialog前的回调
const handleBeforeCloseDialog = async (done: DoneFn) => {
  // 如果还有图片未保存
  if (dialogStatus.value.isSelected) {
    // 询问是否关闭
    const [err, confirm] = await to<string, string>(
      ElMessageBox.confirm("你有图片未上传，是否确定关闭对话框?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }),
    );
    if (err === "cancel") {
      ElMessage({
        type: "info",
        message: "已取消关闭",
      });
    } else if (confirm === "confirm") {
      ElMessage({
        type: "info",
        message: "强制关闭对话框",
      });
      done();
    }
  } else {
    done();
  }
};

/**
 * 处理关闭新增编辑dialog
 */
const handleCloseDialog = () => {
  const currentOrganizationId = dialogData.value.organizationId;
  console.log(currentOrganizationId);
  queryParamsBO.value = Object.assign({}, initQueryParams);
  dialogData.value = Object.assign({}, initDialogData);
  editorRef?.value?.clear();
  dialogStatus.value.isDisabled = false;
  loading.value = false;
  dialogData.value.organizationId = currentOrganizationId;
  dialogStatus.value.cover = "";
  dialogStatus.value.isLinked = false;
  queryParamsBO.value.organizationId = currentOrganizationId;
  currentLinkContent.value = "";
  currentRichContent.value = "";
  console.log(dialogStatus.value.cover);
};

// 获取上传后的url
const getCoverUrl = (url: string) => {
  dialogData.value.cover = url;
};

/**
 * 处理提交按钮
 */
const dialogSubmit = async () => {
  dialogFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (dialogStatus.value.isSelected) {
        const [err, confirm] = await to<string, string>(
          ElMessageBox.confirm("你有图片未上传，是否确定提交?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }),
        );
        if (err === "cancel") {
          ElMessage({
            type: "info",
            message: "已取消关闭",
          });
        } else if (confirm === "confirm") {
          ElMessage({
            type: "info",
            message: "已确定提交",
          });
          // 编辑
          if (dialogData.value.contentType === "1") {
            dialogData.value.content = currentLinkContent.value;
          } else {
            dialogData.value.content = currentRichContent.value;
          }
          if (dialogData.value.id) {
            const [err] = await to<BaseResponse<any>, any>(
              updateSchoolNewsApi(dialogData.value),
            );
            if (!err) {
              ElMessage({
                type: "success",
                message: "修改成功",
              });
              dialogStatus.value.visible = false;
              getNewsList();
            }
          } else {
            // 新增

            console.log(dialogData.value);
            const [err, res] = await to<BaseResponse<any>, any>(
              addSchoolNewsApi(dialogData.value),
            );
            console.log(res);
            if (!err) {
              ElMessage({
                type: "success",
                message: "新增成功",
              });

              dialogStatus.value.visible = false;
              getNewsList();
            }
          }
        }
      } else {
        if (dialogData.value.contentType === "1") {
          dialogData.value.content = currentLinkContent.value;
        } else {
          dialogData.value.content = currentRichContent.value;
        }
        if (dialogData.value.id) {
          // 编辑
          const [err] = await to<BaseResponse<any>, any>(
            updateSchoolNewsApi(dialogData.value),
          );
          if (!err) {
            ElMessage({
              type: "success",
              message: "修改成功",
            });
            dialogStatus.value.visible = false;
            getNewsList();
          }
        }
        // 新增
        else {
          console.log(dialogData.value);

          const [err, res] = await to<BaseResponse<any>, any>(
            addSchoolNewsApi(dialogData.value),
          );
          console.log(res);
          if (!err) {
            ElMessage({
              type: "success",
              message: "新增成功",
            });

            dialogStatus.value.visible = false;
            getNewsList();
          }
        }
      }

      // dialogData.value = Object.assign({}, initQueryParams);
      // handleCloseDialog();
    }
  });
};

/**
 * 查询组织
 */
const handleOrganizationQuery = async () => {
  getOrganizationList();
};

const handleAutoCreateIntroductionChange = (value: boolean) => {
  dialogStatus.value.isDisableIntroduction = value;
};

const queryOrganizationRef = ref();
/**
 * 重置按钮
 */
const resetQuery = () => {
  queryOrganizationRef.value.resetFields();
  getOrganizationList();
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

onMounted(async () => {
  // getNewsList();
  await getRootOrganizationTypeList();
  getOrganizationList();
});
</script>

<style scoped lang="scss">
.innerDialogFooter {
  margin: 0 0 0 830px;
}

.dialogForm {
  .el-form-item {
    width: 100%;
  }
}
</style>
